package com.zhiyou100.video.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.zhiyou100.video.model.User;
import com.zhiyou100.video.service.UserService;
import com.zhiyou100.video.util.Mail;
import com.zhiyou100.video.util.RandomCode;

@Controller
@RequestMapping("/")
public class PwdController {

	@Autowired
	private UserService us;
	
	@RequestMapping("/forget_pwd.do")
	public String login() {
		return "front/user/forget_pwd";
	}

	@RequestMapping("/sendemail.do")
	@ResponseBody
	public Map<String, Object> sendemail(String email,HttpSession session){
		User user = us.selectUserByEmail(email);
		Map<String, Object> maps = new HashMap<>();
		if(user!=null) {
			String code = RandomCode.getCode();
			user.setCaptcha(code);
			Date date = new Date();
			user.setUpdate_time(date);
			us.updateUser(user);
			session.setAttribute("user", user);
			try {
				Mail.send(email, "验证码", "你的验证码是:"+code);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			maps.put("success", true);
		}else {
			maps.put("message", "找不到该邮箱");
		}
		return maps;
	}

	@RequestMapping("/forgetpwd.do")
	public String forgetpwd(String email,String captcha,HttpSession session) {
		if(captcha.equals("")) {
			return "front/user/forget_pwd";
		}else {
			User u = us.selectUserByEmail(email);
			if(u.getCaptcha().equals(captcha)) {
				session.setAttribute("user",u);
				return "front/user/reset_pwd";
			}else {
				return "front/user/forget_pwd";
			}
		}
		
	}
	
	@RequestMapping("/resetpwd")
	public String resetpwd(String password,String pwdAgain,HttpSession session) {
		User u =(User) session.getAttribute("user");
		if(password.equals(pwdAgain)) {
			u.setPassword(DigestUtils.md5Hex(password));
			Date date = new Date();
			u.setUpdate_time(date);
			int i = us.updateUser(u);
			if(i>0) {
				return "front/index";
			}
		}else {
			return "front/user/reset_pwd";
		}
		return null;
	}
	
}
